<?php

namespace app\admin\controller;

use app\admin\model\StoreModel;
use app\admin\services\CityService;
use app\admin\services\QuanGuanMemberService;
use app\admin\services\StoreService;
use app\enums\enum\GenderEnum;
use app\enums\enum\MemberIdentityEnum;
use think\App;

class QuanGuanMemberThreeController extends Common implements ICurd
{
    /**
     * 用户类型
     */
    private $identityList;

    /**
     * 省份列表
     */
    private $provinceList;

    /**
     * 城市列表
     */
    private $cityList;

    /**
     * 区域列表
     */
    private $areaList;

    /**
     * 拳馆列表
     */
    private $storeList;

    public function initialize()
    {
        parent::initialize();
        $this->setIdentityList();
        $this->setProvinceList();
        $this->setCityList();
        $this->setAreaList();
        $this->setStoreList();
    }

    public function index()
    {
        // TODO: Implement index() method.
        if (request()->isPost()) {
            $requestData = input('post.');
            $param['page'] = $requestData['page'] ?: 1;
            $param['pageSize'] = $requestData['limit'] ?: 10;
            $param['key'] = trim($requestData['key']) ?: "";
            $param['identity'] = (int)$requestData['identity'] ?: 3;
            $param['mobile'] = trim($requestData['mobile']) ?: "";
            $param['store_id'] = (int)$requestData['store_id'] ?: 0;
            // 需要查询的字段
            $field = "
                id,
                name,
                status,
                identity,
                create_time,
                mobile,
                gender,
                age,
                province_id,
                city_id,
                area_id,
                store_id,
                image,
                weight
            ";
            $list = $this->getService()->list($param, $field);
            $idenList = array_column($this->identityList, null, 'id');
            $provinceList = array_column($this->provinceList, null, 'id');
            $cityList = array_column($this->cityList, null, 'id');
            $areaList = array_column($this->areaList, null, 'id');
            foreach ($list['data'] as &$item) {
                $item['identity'] = $idenList[$item['identity']]['title'];
                $item['province_id'] = $provinceList[$item['province_id']]['title'];
                $item['city_id'] = $cityList[$item['city_id']]['title'];
                $item['area_id'] = $areaList[$item['area_id']]['title'];
                $item['gender'] = GenderEnum::getEnumInfo($item['gender']);
                $item['create_time'] = date("Y-m-d", $item['create_time']);
                $item['store_name'] = StoreService::makeInstance()->getInfoById($item['store_id'])['title'];
                $item['image'] = env('DOMAIN_PATH') . $item['image'];
            }
            return $this->jsonList($list['data'], $list['total']);
        }
        $this->assign([
            'pageTitle' => '拳馆教练'
        ]);
        return $this->fetch("quan_guan_member/type_index");
    }

    public function create()
    {
        // TODO: Implement create() method.
        if (request()->isPost()) {
            $param = $this->mapping();
            $res = $this->getService()->save($param);
            if ($res) {
                return $this->jsonSuccess("index");
            }
            return $this->jsonError();
        }
        return $this->fetch("quan_guan_member/create");
    }

    public function update($id = 0)
    {
        // TODO: Implement update() method.
        if (request()->isPost()) {
            $param = $this->mapping();
            $res = $this->getService()->save($param, $id);
            if ($res) {
                return $this->jsonSuccess("index");
            }
            return $this->jsonError();
        } else {
            $info = $this->getService()->getInfoById($id);
            $info['store_id'] = $this->storeList[$info['store_id']]['title'];
            $this->assign([
                'info' => json_encode($info, true),
                'infoArr' => $info,
            ]);
            return $this->fetch("quan_guan_member/update");
        }
        return $this->jsonError();
    }

    public function remove()
    {
        // TODO: Implement remove() method.
        if (request()->isPost()) {
            $data = input('post.');
            $id = (int)$data['id'];
            $res = $this->getService()->save(['is_delete' => 2], $id);
            if ($res) {
                return $this->jsonSuccess("index");
            }
            return $this->jsonError();
        }
        return $this->jsonError();
    }

    public function detail()
    {
        // TODO: Implement detail() method.
    }

    public function setStatus()
    {
        // TODO: Implement setStatus() method.
        if (request()->isPost()) {
            $id = input('post.id', 0, 'int');
            $status = input('post.status', 0, 'int');
            $res = $this->getService()->save([
                'status' => $status
            ], $id);
            if ($res) {
                return $this->jsonSuccess('index');
            }
            return $this->jsonError();
        }
        return $this->jsonError();
    }

    private function getService()
    {
        return QuanGuanMemberService::makeInstance();
    }

    private function mapping()
    {
        $data = input('post.');
        $param = [
            'name' => trim($data['name']) ?: "",
            'mobile' => trim($data['mobile']) ?: "",
            'identity' => (int)$data['identity'] ?: 0,
            'age' => (int)$data['age'] ?: 0,
            'gender' => (int)$data['gender'] ?: 0,
            'weight' => (int)$data['weight'] ?: 0,
            'province_id' => (int)$data['province_id'] ?: 0,
            'city_id' => (int)$data['city_id'] ?: 0,
            'area_id' => (int)$data['area_id'] ?: 0,
            'address' => trim($data['address']) ?: "",
            'password' => trim($data['password']) ?: "",
            'image' => trim($data['image']) ?: "",
            'status' => (int)$data['status'] ?: 1,
            'sort' => (int)$data['sort'] ?: 0,
            'desc' => trim($data['desc']) ?: "",
        ];
        if ($param['password'] == "") {
            unset($param['password']);
        } else {
            $param['password'] = password_hash($param['password'], PASSWORD_DEFAULT);
        }
        return $param;
    }

    /**
     * 获取用户类型
     */
    private function setIdentityList()
    {
        $identityList = MemberIdentityEnum::getEnumList();
        foreach ($identityList as $key => $item) {
            $this->identityList[] = [
                'id' => $key,
                'title' => $item
            ];
        }
        $this->assign([
            'identityList' => $this->identityList
        ]);
    }

    /**
     * 获取省份列表
     */
    private function setProvinceList()
    {
        $cityService = new CityService();
        $list = $cityService->getListByLevel(1);
        $this->provinceList = $list->toArray();
        $this->assign([
            'provinceList' => $this->provinceList
        ]);
    }

    /**
     * 获取城市列表
     */
    private function setCityList()
    {
        $cityService = new CityService();
        $list = $cityService->getListByLevel(2);
        $this->cityList = $list->toArray();
        $this->assign([
            'cityList' => $this->cityList
        ]);
    }

    /**
     * 获取区域列表
     */
    private function setAreaList()
    {
        $cityService = new CityService();
        $list = $cityService->getListByLevel(3);
        $this->areaList = $list->toArray();
        $this->assign([
            'areaList' => $this->areaList
        ]);
    }

    /**
     * 获取馆长列表
     */
    public function getCuratorListByType()
    {
        $keyword = trim($this->request->get('keyword'));
        $memberService = new QuanGuanMemberService();
        $list = $memberService->getMemberListByType(4, $keyword, ['id', 'name']);
        $return = [];
        foreach ($list as $item) {
            $return[] = [
                'name' => $item['name'],
                'value' => $item['id'],
            ];
        }
        echo json_encode([
            'code' => 0,
            'msg' => 'success',
            'data' => $return
        ]);
        die;
    }

    /**
     * 获取教练列表
     */
    public function getCoachListByType()
    {
        $keyword = trim($this->request->get('keyword'));
        $memberService = new QuanGuanMemberService();
        $list = $memberService->getMemberListByType(3, $keyword, ['id', 'name']);
        $return = [];
        foreach ($list as $item) {
            $return[] = [
                'name' => $item['name'],
                'value' => $item['id'],
            ];
        }
        echo json_encode([
            'code' => 0,
            'msg' => 'success',
            'data' => $return
        ]);
        die;
    }

    /**
     * 获取拳馆列表
     */
    public function setStoreList()
    {
        $storeService = StoreService::makeInstance();
        $storeList = $storeService->getAllData('id,title');
        $this->storeList = $storeList;
        $this->assign([
            'storeList' => $this->storeList
        ]);
    }

    public function storeTojson()
    {
        $keyword = trim($this->request->get('keyword'));
        $storeService = new StoreService();
        $list = $storeService->getListByTitle($keyword, ['id', 'title']);
        $return = [];
        foreach ($list as $item) {
            $return[] = [
                'name' => $item['title'],
                'value' => $item['id'],
            ];
        }
        echo json_encode([
            'code' => 0,
            'msg' => 'success',
            'data' => $return
        ]);
        die;
    }

}